using Pdf2epub.Interfaces;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;

namespace Pdf2epub.Model
{
    public class BaseObject : INotifyPropertyChanged, IBulkServiceClient
    {
        private readonly List<string> m_BulkChangeList = new List<string>();

        protected BaseObject(IProjectContext projectContext)
        {
            SetProjectContext(projectContext);
        }

        protected BaseObject()
        {
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [XmlIgnore]
        [Browsable(false)]
        public IProjectContext ProjectContext { get; private set; }

        public void ExecuteBulkReleaseAction()
        {
            foreach (string propertyName in m_BulkChangeList)
            {
                TriggerNotificationEvent(propertyName);
            }
        }

        public void SetProjectContext(IProjectContext projectContext)
        {
            ProjectContext = projectContext;
            ProjectContext.BulkService.RegisterClient(this);
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if ((ProjectContext != null) && (ProjectContext.BulkService.IsActive))
            {
                if (m_BulkChangeList.Contains(propertyName))
                    return;

                m_BulkChangeList.Add(propertyName);
            }
            else
            {
                TriggerNotificationEvent(propertyName);
            }
        }

        private void TriggerNotificationEvent(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}